import GlobalConfig from "../../conf"

export default {
  props: {
    //通用平台的参数
    requestTimeout: {
      type: Number
    },
    // 是否已开始锁定
    locking: {
      type: Boolean,
      default: false
    },
    // 加载配置
    loadOptions: {
      type: Object,
      default: () => {
        return {
          url: "",
          formData: {},
          resPath: "data.payload.data",
          resFn: null
        }
      }
    },
    // 请求类型
    ajaxType: {
      type: String,
      default: "POST"
    },
    autoExpandedRootNode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loadDataRes: null,
      cancelAxios: null
    }
  },
  computed: {},
  watch: {
    loadOptions: {
      handler(val) {
        let option = {
          url: "",
          formData: {},
          resPath: "data.payload.data",
          resFn: null
        }
        this._loadOptions = _.merge({}, option, val)
      },
      immediate: true
    }
  },
  created() {},
  mounted() {
    this.platformInit()
  },
  methods: {
    //初始化
    async platformInit() {
      !this.locking && this.getTableListData()
    },
    //获取列表数据
    getTableListData() {
      return new Promise(async (resolve) => {
        if (this._loadOptions.url == "") return resolve(false)

        this.$refs.virtualTreeTable.loadingEd = true
        //取消之前的请求
        this.cancelAxios && this.cancelAxios()

        try {
          let _data = _.toUpper(this.ajaxType) == "POST" ? { data: this._loadOptions.formData } : { params: this._loadOptions.formData }
          const CancelToken = GlobalConfig.request.CancelToken // axios的CancelToken
          let res = await GlobalConfig.request({
            method: this.ajaxType,
            url: this._loadOptions.url,
            timeout: this.requestTimeout ? this.requestTimeout : undefined,
            cancelToken: new CancelToken((c) => (this.cancelAxios = c)),
            ..._data
          })
          if (res && res !== "cancelAxios") {
            this.loadDataRes = res
            let resData = this._loadOptions.resFn ? this._loadOptions.resFn(res) : _.get(res, this._loadOptions.resPath, [])

            this._loadTreeData(this.toVirtualTree(resData)).then((res) => {
              this.autoExpandedRootNode && this.setTreeExpand(resData[0], true)
            })
            this.$emit("onPageLoad", { datas: resData, response: res })
            resolve({ datas: resData, response: res })
          }
        } catch (err) {}
        this.$refs.virtualTreeTable.loadingEd = false
        resolve(false)
      })
    },
    // 选中满足条件的节点
    handleSelectNode({ key, value }, flag = true) {
      return new Promise((resolve) => {
        // 找到满足当前条件的节点, 和父节点的路径
        const node = this.getNode(key, value)
        if (!node) return resolve(false)

        // 展开所有父节点
        const { item: fitNode, paths: fitNodeParentPaths } = node
        const { fullTreeData, treeOpts } = this
        let { children } = treeOpts // 树配置 chidlren 的 childKey
        const expandeArr = []
        fitNodeParentPaths.forEach((item, index) => {
          if (item !== children) {
            const node = _.get(fullTreeData, fitNodeParentPaths.slice(0, index + 1))
            if (node && node[children] && node[children].length) {
              expandeArr.push(node)
            }
          }
        })

        //展开所有节点, 选中节点，滚动到该节点
        this.setTreeExpand(expandeArr, true).then(() => {
          flag ? this.$refs.virtualTreeTable.triggerCurrentRowEvent(null, { row: fitNode }) : this.$refs.virtualTreeTable.setCurrentRow(fitNode, false)
          this.$emit("currentChange")
          setTimeout(() => {
            this.$refs.virtualTreeTable.scrollToRow(fitNode)
          }, 50)
          return resolve({ node: fitNode, paths: fitNodeParentPaths })
        })
      })
    },
    // 获取满足条件的节点
    getNode(key, value) {
      let node
      for (const [item, itemMapValue] of this.fullTreeRowMap) {
        if (item[key] === value) {
          node = itemMapValue
          break
        }
      }
      return node
    }
  },
  activated() {},
  deactivated() {},
  beforeDestroy() {},
  destroyed() {}
}
